
package net.vinote.smart.platform.module.database;

import java.sql.Connection;
import java.sql.SQLException;

import net.vinote.smart.platform.base.Platform;
import net.vinote.smart.platform.comm.PlatformConst;
import net.vinote.smart.platform.module.dbpool.DataBasePoolFactory;


/**
 * 数据库工厂类,用于获取数据库连接的实例
 * 
 * @author zjw 2011-10-25
 */
public final class DBFactory
{
	private static DBFactory factory = new DBFactory();

	private DBFactory()
	{
		System.setProperty(PlatformConst.SYSTEM_CFG_DATABASE_DRIVER, Platform
				.getAttribute(PlatformConst.SYSTEM_CFG_DATABASE_DRIVER)
				.toString());
		System.setProperty(PlatformConst.SYSTEM_CFG_DATABASE_URL, Platform
				.getAttribute(PlatformConst.SYSTEM_CFG_DATABASE_URL).toString());
		System.setProperty(PlatformConst.SYSTEM_CFG_DATABASE_USERNAME, Platform
				.getAttribute(PlatformConst.SYSTEM_CFG_DATABASE_USERNAME)
				.toString());
		System.setProperty(PlatformConst.SYSTEM_CFG_DATABASE_PASSWORD, Platform
				.getAttribute(PlatformConst.SYSTEM_CFG_DATABASE_PASSWORD)
				.toString());
		System.setProperty(
				PlatformConst.SYSTEM_CFG_DATABASE_MINCONNECT,
				Platform.getAttribute(
						PlatformConst.SYSTEM_CFG_DATABASE_MINCONNECT)
						.toString());
		System.setProperty(
				PlatformConst.SYSTEM_CFG_DATABASE_MAXCONNECT,
				Platform.getAttribute(
						PlatformConst.SYSTEM_CFG_DATABASE_MAXCONNECT)
						.toString());
		System.setProperty(
				PlatformConst.SYSTEM_CFG_DATABASE_CONNECTTIMEOUT,
				Platform.getAttribute(
						PlatformConst.SYSTEM_CFG_DATABASE_CONNECTTIMEOUT)
						.toString());
	}

	public void destroy()
	{
		DataBasePoolFactory.getFactory().destroy();
	}

	public static DBFactory getFactory()
	{
		return factory;
	}

	private Connection getConnection()
	{
		return DataBasePoolFactory.getFactory().getConnection();
	}

	public DBTransaction getTransaction()
	{
		Connection conn = getConnection();
		if (conn == null)
			throw new NullPointerException(
					"无法建立数据库连接:[Driver:"
							+ Platform
									.getAttribute(PlatformConst.SYSTEM_CFG_DATABASE_DRIVER)
							+ ",URL:"
							+ Platform
									.getAttribute(PlatformConst.SYSTEM_CFG_DATABASE_URL)
							+ ",USERNAME:"
							+ Platform
									.getAttribute(PlatformConst.SYSTEM_CFG_DATABASE_USERNAME)
							+ ",PASSWORD:"
							+ Platform
									.getAttribute(PlatformConst.SYSTEM_CFG_DATABASE_PASSWORD)
							+ "]");
		return new DBTransaction(conn);
	}

	/**
	 * 测试数据库连接是否接通
	 * 
	 * @return
	 * @throws SQLException
	 */
	public boolean test() throws SQLException
	{
		Connection conn = getConnection();
		if (conn != null)
			return conn.isValid(3000);
		return false;
	}
}
